<?php

namespace app\admin\model;

use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\admin\model\user\money\Log as UserMoneyLog;
use think\Model;

class User extends Model
{

    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'prevtime_text',
        'logintime_text',
        'jointime_text'
    ];

    protected $schema = [
        'id' => 'int',
        'shopping_integral' => 'bigint',
        'coupon_integral' => 'bigint',
        'promotion_bonus' => 'bigint',
        'green_integral' => 'bigint',
        'money' => 'bigint',
    ];


    public function getOriginData()
    {
        return $this->origin;
    }

    protected static function init()
    {
        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            //如果有修改密码
            if (isset($changed['password'])) {
                if ($changed['password']) {
                    $salt = \fast\Random::alnum();
                    $row->password = \app\common\library\Auth::instance()->getEncryptPassword($changed['password'], $salt);
                    $row->salt = $salt;
                } else {
                    unset($row->password);
                }
            }
        });


        self::beforeUpdate(function ($row) {
            $changedata = $row->getChangedData();
            $origin = $row->getOriginData();
            
            if (isset($changedata['score']) && (int)$changedata['score'] !== (int)$origin['score']) {
                ScoreLog::create(['user_id' => $row['id'], 'score' => $changedata['score'] - $origin['score'], 'before' => $origin['score'], 'after' => $changedata['score'], 'memo' => '管理员变更积分']);
            }
        });
    }

    public function getGenderList()
    {
        return ['1' => __('Male'), '0' => __('Female')];
    }

    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden')];
    }


    public function getPrevtimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['prevtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getLogintimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['logintime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getJointimeTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['jointime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPrevtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setLogintimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setJointimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setBirthdayAttr($value)
    {
        return $value ? $value : null;
    }

    public function group()
    {
        return $this->belongsTo('UserGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }



    // 转化积分到权益值
    public function convertEquity($shoppingUsed, $couponUsed, $actualEquity = null)
    {
        // 记录变动前的值
        $beforeShopping = $this->shopping_integral;
        $beforeCoupon = $this->coupon_integral;
        $beforeMoney = $this->money;
        
        // 如果提供了实际转化的权益值，则使用该值，否则使用原计算方式
        $equityToAdd = ($actualEquity !== null) ? $actualEquity : ($shoppingUsed + $couponUsed);
        
        // 更新数据
        $this->save([
            'shopping_integral' => $this->shopping_integral - $shoppingUsed,
            'coupon_integral' => $this->coupon_integral - $couponUsed,
            'money' => $this->money + $equityToAdd,
        ]);
        
        // 记录购物积分变动
        if ($shoppingUsed > 0) {
            UserMoneyLog::recordShoppingIntegral(
                $this->id,
                -$shoppingUsed,
                $beforeShopping,
                $this->shopping_integral,
                '购物积分转换为权益值'
            );
        }
        
        // 记录消费券变动
        if ($couponUsed > 0) {
            UserMoneyLog::recordCouponIntegral(
                $this->id,
                -$couponUsed,
                $beforeCoupon,
                $this->coupon_integral,
                '消费券转换为权益值'
            );
        }
        
        // 记录权益值增加
        if ($equityToAdd > 0) {
            UserMoneyLog::recordEquityValue(
                $this->id,
                $equityToAdd,
                $beforeMoney,
                $this->money,
                '转换获得权益值' . (($actualEquity !== null && $actualEquity != ($shoppingUsed + $couponUsed)) ? '（按比例计算）' : '')
            );
        }

        // 推广红包

        // 绿色积分
        
    }

}
